package controller

import (
	"ginfast/api/mall/dto"
	"ginfast/api/mall/model"
	"ginfast/pkg/ctx"
	"ginfast/pkg/orm"
	"ginfast/util"

	"github.com/gin-gonic/gin"
)

// Brand 品牌
type Brand struct {
}

// ListHandler 列表
func (o *Brand) ListHandler(c *gin.Context) {
	var p dto.Where
	if err := c.ShouldBind(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	var data []model.Brand
	total, _ := p.DbModelWhere(&model.Brand{}).Find(&data)
	ctx.JSONWriteTotal(total, data, c)
}

// GetHandler 查询
func (o *Brand) GetHandler(c *gin.Context) {
	util.QueryByID(&model.Brand{}, c)
}

// AddHandler 新增
func (o *Brand) AddHandler(c *gin.Context) {
	var p model.Brand
	//获取参数
	if err := c.ShouldBind(&p.BrandOpt); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	if err := orm.DbCreate(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(nil, c)
}

// UpdateHandler 更新
func (o *Brand) UpdateHandler(c *gin.Context) {
	var p model.Brand
	//获取参数
	if err := c.ShouldBind(&p.BrandOpt); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	if err := orm.DbUpdateModel(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(nil, c)
}

type showStatus struct {
	IDS        string `form:"ids"`
	ShowStatus string `form:"showStatus"`
}

func (o *Brand) UpdateShowHandler(c *gin.Context) {
	var p showStatus
	if err := c.ShouldBind(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ids := util.StringSplit(p.IDS, ",")
	if err := orm.DbUpdateByID(&model.Brand{}, ids, orm.H{"ShowStatus": p.ShowStatus}); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(nil, c)
}

// UpdateFactoryHandler 更新
func (o *Brand) UpdateFactoryHandler(c *gin.Context) {
	var p model.Brand
	//获取参数
	if err := c.ShouldBind(&p.BrandOpt); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	if err := orm.DbUpdateFields(&p, "FactoryStatus"); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(nil, c)
}

// DeleteHandler 删除
func (o *Brand) DeleteHandler(c *gin.Context) {
	util.Deletes(&model.Brand{}, c)
}

func (o Brand) Routers(r *gin.RouterGroup) {
	r.GET("/list", o.ListHandler)
	r.GET("/:id", o.GetHandler)
	r.POST("", o.AddHandler)
	r.PUT("", o.UpdateHandler)
	r.POST("/showStatus", o.UpdateShowHandler)
	r.POST("/factoryStatus", o.UpdateFactoryHandler)
	r.DELETE("", o.DeleteHandler)
}
